<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('关联账号')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('关联账号')" clearable @change="changeUser" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('姓名')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('姓名')" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('性别')" prop="sex">
            <dictSelect
              v-model="form.sex"
              :clearable="true"
              dictionary="sys_user_sex"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出生年月')" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              clearable
              style="width: 200px"
              type="month"
              value-format="yyyy-MM"
              :placeholder="$t('出生年月')"
              @change="calculateAge"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证件类型')" prop="idType">
            <dictSelect
              v-model="form.idType"
              :clearable="true"
              dictionary="hr_id_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证件号码')" prop="idNum">
            <el-input v-model="form.idNum" :placeholder="$t('证件号码')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('年龄')" prop="age">
            <el-input v-model="form.age" :placeholder="$t('年龄')" disabled show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('民族')" prop="nation">
            <el-input v-model="form.nation" :placeholder="$t('民族')" show-word-limit maxlength="10" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所在部门')" prop="deptId">
            <DeptSelect v-model="form.deptId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('政治面貌')"
            prop="politicalOutlook"
          >
            <dictSelect
              v-model="form.politicalOutlook"
              :clearable="true"
              dictionary="hr_political_outlook"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('职位')" prop="position">
            <el-select v-model="form.position" filterable>
              <el-option
                v-for="(item) in dict.hrPositions"
                :key="item.id"
                :label="$t(item.postName)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('入职时间')" prop="entryTime">
            <DatePicker
              v-model="form.entryTime"
              type="date"
              :placeholder="$t('入职时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('员工类型')" prop="staffType">
            <dictSelect
              v-model="form.staffType"
              :clearable="true"
              dictionary="hr_staff_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('工作年限')" prop="workingYear">
            <el-input v-model="form.workingYear" :placeholder="$t('工作年限')" show-word-limit maxlength="10" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('户籍类型')">
            <dictSelect
              v-model="form.censusRegisterType"
              :clearable="true"
              dictionary="hr_census_register_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('户籍所在地')" prop="censusRegisterAddress">
            <el-input v-model="form.censusRegisterAddress" :placeholder="$t('户籍所在地')" show-word-limit maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('现住地')" prop="currentAddress">
            <el-input v-model="form.currentAddress" :placeholder="$t('现住地')" show-word-limit maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同或协议类型')" prop="contractType">
            <dictSelect
              v-model="form.contractType"
              :clearable="true"
              dictionary="hr_contract_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item :label="$t('国籍')" prop="international">
            <dictSelect
              v-model="form.international"
              :clearable="true"
              dictionary="hr_international"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('婚姻状况')" prop="marriage">
            <dictSelect
              v-model="form.marriage"
              :clearable="true"
              dictionary="marriage"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('个人邮箱')" prop="email">
            <el-input v-model="form.email" :placeholder="$t('个人邮箱')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('手机号码')" prop="phone">
            <el-input v-model="form.phone" :placeholder="$t('手机号码')" show-word-limit maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同或协议生效时间')" prop="takeEffectTime">
            <DatePicker
              v-model="form.takeEffectTime"
              type="date"
              :placeholder="$t('合同或协议生效时间')"
              @change="calculationTerm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同或协议终止时间')" prop="terminationTime">
            <DatePicker
              v-model="form.terminationTime"
              type="date"
              :placeholder="$t('合同或协议终止时间')"
              @change="calculationTerm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同或协议期限')" prop="contractTerm">
            <el-input v-model="form.contractTerm" :placeholder="$t('合同或协议期限')" show-word-limit disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('续签时间')" prop="renewalTime">
            <DatePicker
              v-model="form.renewalTime"
              type="date"
              :placeholder="$t('续签时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('转正时间')" prop="positiveTime">
            <DatePicker
              v-model="form.positiveTime"
              type="date"
              :placeholder="$t('转正时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('状态')" prop="status">
            <dictSelect
              v-model="form.status"
              :clearable="true"
              dictionary="hr_entry_status"
              @change="onChangeHr"
            />
          </el-form-item>
        </el-col>
        <el-col v-show="form.status !== 'zz'" :span="12">
          <el-form-item :label="$t('离职时间')" :prop="form.status=='zz'?'':'quitTime'">
            <DatePicker
              v-model="form.quitTime"
              type="date"
              :placeholder="$t('离职时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('擅长领域')" prop="goodAtField">
            <el-input v-model="form.goodAtField" type="textarea" :placeholder="$t('擅长领域')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('投资理念')" prop="investmentPhilosophy">
            <el-input v-model="form.investmentPhilosophy" type="textarea" :placeholder="$t('投资理念')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('优秀投资案例')" prop="excellentInvestmentCase">
            <el-input v-model="form.excellentInvestmentCase" type="textarea" :placeholder="$t('优秀投资案例')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('所获荣誉')" prop="honours">
            <el-input v-model="form.honours" type="textarea" :placeholder="$t('所获荣誉')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <!--保存 取消按钮-->
      <save-btn has-permi="hrBase:hrBase" />
    </div>
  </div>
</template>

<script>
import { saveHrBase, getHrBase, checkUserId } from '@/api/oa/hr/hrBase'
import { listPost } from '@/api/system/post'
import { getUser } from '@/api/system/user'
export default {
  components: { },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        userId: [{ required: false, validator: this.checkUser, trigger: 'blur' }],
        name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
        // sex: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // birthDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // idNum: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // deptId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // politicalOutlook: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // position: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // entryTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // staffType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // workingYear: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // contractType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // international: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // marriage: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // email: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // phone: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // terminationTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // takeEffectTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // idType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        // quitTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      dict: {
        hrPositions: []
      }
    }
  },
  created() {
    this.initDict()
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      if (data != null && data.id !== undefined) {
        this.loading = true
        getHrBase(data.id).then(response => {
          this.$nextTick(() => {
            this.form = response.data
            this.calculateAge()
            this.loading = false
            if (this.form.contractTerm === undefined || this.form.contractTerm === null || this.form.contractTerm === '') { this.calculationTerm() }
          })
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    onChangeHr(value) {
      if (value === 'zz') {
        this.form.quitTime = undefined
      }
    },
    changeUser(val) {
      if (val && val !== this.form.userId) {
        getUser(val).then(response => {
          console.log(response)
          const userInfo = this.isEmpty(response.data) ? {} : response.data
          this.form.name = userInfo.nickName
          this.form.sex = userInfo.sex
          this.form.deptId = userInfo.deptId
          this.form.phone = userInfo.phonenumber
          this.form.entryTime = userInfo.entryTime
          this.form.email = userInfo.email
          this.form.position = this.isEmpty(response.datas) ? undefined : (this.isEmpty(response.datas.postIds) ? undefined : response.datas.postIds[0])
        })
      }
    },
    calculateAge() {
      if (!this.form.birthDate) {
        // 如果没有选择日期，则不计算年龄
        this.form.age = ''
      } else {
        // 获取当前日期
        const now = new Date()
        const currentYear = now.getFullYear()
        const currentMonth = now.getMonth() + 1 // JavaScript中月份是从0开始的，所以加1

        // 解析选择的出生年月
        const birthDate = this.form.birthDate.split('-')
        const birthYear = parseInt(birthDate[0], 10)
        const birthMonth = parseInt(birthDate[1], 10)

        let age = currentYear - birthYear

        // 如果当前月份小于出生月份，则年龄需要减一
        if (currentMonth < birthMonth) {
          age--
        }
        this.form.age = age
      }
  },
  // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        name: undefined,
        userId: undefined,
        sex: undefined,
        birthDate: undefined,
        idType: undefined,
        idNum: undefined,
        age: undefined,
        nation: undefined,
        deptId: undefined,
        politicalOutlook: undefined,
        position: undefined,
        entryTime: undefined,
        censusRegisterType: undefined,
        censusRegisterAddress: undefined,
        currentAddress: undefined,
        contractType: undefined,
        international: undefined,
        workplaceType: undefined,
        marriage: undefined,
        email: undefined,
        phone: undefined,
        takeEffectTime: undefined,
        terminationTime: undefined,
        contractTerm: undefined,
        renewalTime: undefined,
        positiveTime: undefined,
        quitTime: undefined,
        goodAtField: undefined,
        investmentPhilosophy: undefined,
        excellentInvestmentCase: undefined,
        honours: undefined,
        staffType: undefined,
        status: 'zz',
        workingYear: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveHrBase(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    calculationTerm() {
      if (this.form.terminationTime === undefined || this.form.terminationTime === null ||
        this.form.takeEffectTime === undefined || this.form.takeEffectTime === null
      ) {
        this.form.contractTerm = undefined
      } else {
        let date1 = this.form.terminationTime.split('-')
        date1 = parseInt(date1[0]) * 12 + parseInt(date1[1])
        let date2 = this.form.takeEffectTime.split('-')
        date2 = parseInt(date2[0]) * 12 + parseInt(date2[1])
        this.$set(this.form, 'contractTerm', ((date1 - date2) / 12).toFixed(1))
      }
    },
    initDict() {
      // 职位
      listPost({}).then(response => {
        this.dict.hrPositions = response.rows
      })
    },
    // 同一个用户不能再次录入
    async checkUser(rule, value, callback) {
      if (this.form.userId === undefined || this.form.userId === '') {
        return
      }
      var check = {
        userId: this.form.userId,
        id: this.form.id
      }
      var checkRes = await checkUserId(check)
      if (checkRes) {
        callback()
      } else {
        callback(new Error(this.$t('该员工已存在，不能重复添加')))
      }
    }
  }

}
</script>
